package kr.co.bettersoft.usedmarketandroid.fragment;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import kr.co.bettersoft.usedmarketandroid.activity.R;
import kr.co.bettersoft.usedmarketandroid.common.CommonConstant;

import org.apache.http.util.EncodingUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

/**
 * @author blue
 *
 */
public class FragmentMenu1Home extends Fragment{			
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	String TAG = "FragmentMenu1Home";

	// 웹뷰 관련
	String loadingURL = "";
	String isGetMethod = "";
	String webViewTitle = "";
	String postData;
	
	// 화면 관련
	ProgressBar pb1;		// 중단 로딩 진행바

	// 타이틀바
	View title_layout;
	Button topNaviCloseBtn; 		// 상단 닫기 버튼
	TextView webview_title;		// 상단 타이틀

	// 동적 웹뷰
	LinearLayout contents;
	WebView wv;

	// 파일 첨부 관련
	private ValueCallback<Uri> mUploadMessage;
	private final static int FILECHOOSER_RESULTCODE = 1;
	
	///////////////////////////////////////////////////////////////////////////////////////////////////////	

	// 핸들러
	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			try{
				Bundle b = msg.getData();		
				if(b.getInt("order")==1){
					// 프로그래스바 실행
					pb1.setVisibility(View.VISIBLE);
				}else if(b.getInt("order")==2){
					// 프로그래스바  종료
					pb1.setVisibility(View.INVISIBLE);
				}
//				if(b.getInt("showErrToast")==1){
//					Toast.makeText(myWebView.this, getString(R.string.error_message), Toast.LENGTH_SHORT).show();
//					// 페이지를 불러오는데 실패했습니다.\n잠시후 다시 시도해주시기 바랍니다.		
//				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	};

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	//	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	//		
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.fragment_menu1_home, null);
		pb1=(ProgressBar) view.findViewById(R.id.webview_progressbar1);
		
		contents = (LinearLayout) view.findViewById(R.id.webview_linear_layout);
		wv = new WebView(returnThis());

		// 웹뷰 전체화면 만들기
		wv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT , LayoutParams.MATCH_PARENT));
		
		wv.addJavascriptInterface(new AndroidBridge(), "hybrid");
		wv.getSettings().setJavaScriptEnabled(true);		 // JavaScript 허용.
		wv.setWebViewClient(new MyWebViewClient());  // WebViewClient 지정       
		wv.setWebChromeClient(new MyWebChromeClient());
		
//		wv.setOnTouchListener(new OnTouchListener() {
//			@Override
//			public boolean onTouch(View v, MotionEvent event) {
//				Log.d(TAG,"v.getScrollY():"+v.getScrollY());
//				// TODO Auto-generated method stub
//				return false;
//			}
//		});
		contents.addView(wv);
		
		loadingURL = CommonConstant.MENU_1_HOME_URL; 
		isGetMethod = "true";		// false 
		
		if(loadingURL.length()>0){
			postData = "";	
			if(isGetMethod!=null && isGetMethod.equals("true")){
				// get 방식
				Log.d(TAG,"use get method");
				wv.loadUrl(loadingURL);
			}else{
				wv.postUrl(loadingURL, EncodingUtils.getBytes(postData, "BASE64"));
			}
		}else{
//			Toast.makeText(myWebView.this, R.string.cant_find_url, Toast.LENGTH_SHORT).show();
		}

		
		/**
		 * for test.. ### 
		 */
//		Button top_navi_close_btn = (Button) view.findViewById(R.id.top_navi_close_btn);
//		top_navi_close_btn.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				// 부모 액티비티의 함수 호출							
//				Activity parentActivity = getActivity();
//				if(parentActivity instanceof FragmentMain) {
//				    ((FragmentMain) parentActivity).createChatRoom("40", "01073584140");		// test 용. 40~45
//				}
//			}
//		});
		
		
		
		
		
		
		
		return view;
	}

	
	/**
	 * MyWebViewClient
	 * 페이지 로드, 완료 이벤트발생 가능한 웹뷰 클라이언트
	 *
	 */
	private class MyWebViewClient extends WebViewClient {
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// 마켓 링크 연결
			if(url.contains("market://")){
				Uri uri = Uri.parse(url);  	// ex)"market://details?id=kr.co.bettersoft.checkmileage.activities"
				Intent it = new Intent(Intent.ACTION_VIEW, uri);  
				startActivity(it) ;
			}else{
				// 일반
				view.loadUrl(url);
			}
			return true;
		}
		/**
		 * onPageFinished
		 * 로딩 끝나면 프로그래스바 숨기고 재로딩 가능하도록한다
		 *
		 * @param view
		 * @param url
		 * @return
		 */
		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			hidePb();
		}
		/**
		 * onPageStarted
		 * 웹뷰 로딩 시작하면 시간 재서 로딩 안되면 멈추고 알린다.
		 *
		 * @param view
		 * @param url
		 * @param favicon
		 * @return
		 */
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			showPb();
		}
	}

	/**
	 * WebChromeClient 를 상속하는 클래스이다.
	 * alert 이나 윈도우 닫기 등의 web 브라우저 이벤트를 구하기 위한 클래스이다.
	 * @author johnkim
	 */
	private class MyWebChromeClient extends WebChromeClient {
		//Javascript alert 호출 시 실행
		@Override
		public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
			final JsResult finalRes = result;
			//AlertDialog 생성
			new AlertDialog.Builder(view.getContext())
			.setMessage(message)
			.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					finalRes.confirm(); 
				}
			})
			.setCancelable(false)
			.create()
			.show();
			return true;
		}
		
		
		
		/*
		 * 파일 첨부를 위한 처리
		 */
		 // For Android < 3.0
		 public void openFileChooser( ValueCallback<Uri> uploadFile ){
		 openFileChooser( uploadFile, "" );
		 }
		 // For Android 3.0+
		 public void openFileChooser( ValueCallback<Uri> uploadFile, String acceptType ){
			 mUploadMessage = uploadFile;
		 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
		 i.addCategory(Intent.CATEGORY_OPENABLE);
		 i.setType("*/*");
		 startActivityForResult( Intent.createChooser( i, "File Chooser" ), FILECHOOSER_RESULTCODE );
		 }
		 // For Android 4.1+
		 public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {
		 openFileChooser( uploadFile, "" );
		 }
	}

	/**
	 * 파일 첨부 관련
	 */
	 @Override
	public  void onActivityResult(int requestCode, int resultCode,
	         Intent intent) {
		 super.onActivityResult(requestCode, resultCode, intent);
	     if (requestCode == FILECHOOSER_RESULTCODE) {
	         if (null == mUploadMessage){
	        	 Log.d(TAG,"null == mUploadMessage");
	             return;
	         }
	         Log.d(TAG,"resultCode::"+resultCode);
	         int RESULT_OK = -1;		//int RESULT_OK = -1;	
	         Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
	         mUploadMessage.onReceiveValue(result);
	         mUploadMessage = null;
	     }
	 }
	
	/**
	 * Bridge Class
	 * 
	 */
	private class AndroidBridge {
		/**
		 * Server 에서 전화번호를 보내줄때만 전화를 걸 수 있다.
		 * 
		 * @param phoneNumber
		 */
		public void setCallingPhoneNumber(final String phoneNumber) {
			handler.post(new Runnable() {
				
				public void run() {
					// TODO Auto-generated method stub
					Log.i(TAG, "Received phoneNumber from Server : " + phoneNumber);
					
					if(("").equals(phoneNumber)) {
						Toast.makeText(returnThis(), "전화번호가 없습니다." + "\n" + "확인해 주세요.", Toast.LENGTH_SHORT).show();
					} else {
						Log.d(TAG, "Calling Phone.");
						startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)));
					}
				}
			});
		}
		
		/**
		 * SMS
		 * 
		 * @param phoneNumber
		 */
		public void setSMSPhoneNumber(final String phoneNumber) {
			handler.post(new Runnable() {
				public void run() {
					// TODO Auto-generated method stub
					Log.i(TAG, "Received phoneNumber from Server : " + phoneNumber);
					
					if(("").equals(phoneNumber)) {
						Toast.makeText(returnThis(), "전화번호가 없습니다." + "\n" + "확인해 주세요.", Toast.LENGTH_SHORT).show();
					} else {
						Log.d(TAG, "SMS Phone.");
						Intent sendIntent = new Intent(Intent.ACTION_VIEW);         
						sendIntent.setData(Uri.parse("sms:" + phoneNumber));
//						sendIntent.putExtra("sms_body", x); 
						startActivity(sendIntent);
					}
				}
			});
		}
		

		
		// 종료
		public void finishActivity(){
			Log.d(TAG,"finish called");
			handler.post(new Runnable() {
				public void run() {
					// 부모 액티비티의 닫기 기능 호출									// 안되면 자체 종료시켜야 하는데 자체 finish 를 호출할 수 없으므로..  getActivity().finish(); 사용할것
					Activity parentActivity = getActivity();
					if(parentActivity instanceof FragmentMain) {
					    ((FragmentMain) parentActivity).confirmFinish();
					}
				}
			});
		}
		
		// 사용자 아이디(전화번호)를 전달해준다.
		public void jsGetUserPhoneNumber(){
			handler.post(new Runnable() {
				public void run() {
					SharedPreferences sharedPrefCustom = returnThis().getSharedPreferences(CommonConstant.prefName,
							Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
					String phoneNumber = sharedPrefCustom.getString("phoneNumber", "");		// test
					Log.d(TAG,"phoneNumber::"+phoneNumber);
					 wv.loadUrl("javascript:setUserPhoneNumber('"+phoneNumber+"');");
				}
			});
		}
		
		// 사용자 아이디(전화번호)를 전달해준다.
		public void sendPreference(){		
			handler.post(new Runnable() {
				public void run() {
					SharedPreferences sharedPrefCustom = returnThis().getSharedPreferences(CommonConstant.prefName,
							Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
					String phoneNum = sharedPrefCustom.getString("phoneNum", "");		// test
					String strCountry = sharedPrefCustom.getString("strCountry", "");		// test
					 wv.loadUrl("javascript:setPreference('"+phoneNum+"' , '" + strCountry + "');");	//					 setPreference ('사용자 휴대전화번호', '국가코드');
				}
			});
		}
		
		/*
		 * 채팅방 생성한다
		 *  제품id, 판매자 전화번호로 생성. (+내 번호는 자체적으로 가지고 있음)
		 */
		public void createChatRoom(final String productId, final String sellerPhoneNum){		
			handler.post(new Runnable() {
				public void run() {
					Log.d(TAG,"createChatRoom");
					// 부모 액티비티의 함수 호출							
					Activity parentActivity = getActivity();
					if(parentActivity instanceof FragmentMain) {
						// ((FragmentMain) parentActivity).createChatRoom("40", "01073584140");		// test 용. 40~45
					    ((FragmentMain) parentActivity).createChatRoom(productId, sellerPhoneNum);				
					}
				}
			});
		}
		
	}
	///////////////////////////////////////////////////////////////////////////////////////////////////////
	// 유틸

	public Context returnThis(){
		return getActivity();
	}

	/**
	 * showPb
	 *  중앙 프로그래스바 가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showPb(){
		new Thread( 
				new Runnable(){
					public void run(){
						Message message = handler .obtainMessage();
						Bundle b = new Bundle();
						b.putInt( "order" , 1);
						message.setData(b);
						handler .sendMessage(message);
					}
				}
		).start();
	}
	/**
	 * hidePb
	 *  중앙 프로그래스바 비가시화한다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void hidePb(){
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler .obtainMessage();
						Bundle b = new Bundle();
						b.putInt( "order" , 2);
						message.setData(b);
						handler .sendMessage(message);
					}
				}
		).start();
	}

	/**
	 * showErrMsg
	 *  화면에 error 토스트 띄운다
	 *
	 * @param
	 * @param
	 * @return
	 */
	public void showErrMsg(){			
		new Thread(
				new Runnable(){
					public void run(){
						Message message = handler.obtainMessage();				
						Bundle b = new Bundle();
						b.putInt("showErrToast", 1);
						message.setData(b);
						handler.sendMessage(message);
					}
				}
		).start();
	} 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	/**
	 * back button
	 */
	public void goBack(){
//		wv.loadUrl("javascript:alert('"+"goback"+"');");
		wv.loadUrl("javascript:back();");
	}
	
//	/**
//	 * onStop
//	 *  액티비티 정지할때 웹뷰 로딩도 정지한다
//	 *
//	 * @param
//	 * @param
//	 * @return
//	 */
//	@Override
//	public void onStop(){
//		if(wv!=null){
//			runOnUiThread(new Runnable(){
//				public void run(){
//					wv.stopLoading();	
//				}
//			});
//		}
//		super.onStop();
//	}
}
